//
//  OAuthViewController.swift
//  MicroBlog
//
//  Created by 002 on 15/10/17.
//  Copyright © 2015年 002. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        print("\(view)")
        
        // 加载网络访问页面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
        
    }
    
    //MARK: 设置界面
    override func loadView() {
        
        // 直接替换View，不需要添加到View上面
        view = webView
        // 设置代理
        webView.delegate = self
        
        title = "登录新浪微博"
        
        // 设置导航栏的按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }
    
    // 关闭当前界面
   @objc private func close() {
    
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 自动填充用户名和密码 － web 注入（以代码的方式向web页面添加内容）
    @objc private func autoFill() {
        
        let js = "document.getElementById('userId').value = '13163068587';" +
        "document.getElementById('passwd').value = '247689520';"
        
        // 让 webView 执行 注入代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }

}

// MARK: - 监听网页加载情况 和 请求用户信息
extension OAuthViewController : UIWebViewDelegate{
    
    /// 监听网页每次加载
    ///
    /// :param: webView        webView
    /// :param: request        request 网页请求
    /// :param: navigationType navigationType
    ///
    /// :returns:
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 目标:如果是百度就停止加载
        //MARK:下面注释的代码用于观察界面从加载webView开始后跳槽登录的情况，观察接口的参数
        print("\(request)")
        print("\(request.URL?.host)")
        print("\(request.URL?.query)")
        
        // 1. 判断是否是百度地址
        guard let url = request.URL where url.host == "www.baidu.com" else {
            print("不是百度地址")
            return true
        }

        // 2.判断code是否存在
        guard let query = url.query where query.hasPrefix("code=") else {
            print("取消授权")
            return false
        }
        
        // 3.提取code
        let code = query.substringFromIndex("code=".endIndex)
        print("授权码：\(code)")
        
        // 4.加载Token
        UserAccountViewModel.shareUserAccount.loadAccessToken(code) { (isSucceed) -> () in
            
            if isSucceed {
                
              self.dismissViewControllerAnimated(true, completion: { () -> Void in
                
                // 移除进度框
                SVProgressHUD.dismiss()
                // 发送通知
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "welcome")
              })
            } else
            {
                SVProgressHUD.showInfoWithStatus("亲，您的网络不给力")
                delay(0.5, callBack: { () -> () in
                    self.close()
                })
                print("加载失败")
            }
        }
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        // 加载网页的时候出现进度框
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        // 加载完毕后移除进度框
        SVProgressHUD.dismiss()
    }
}


